/**
 * 生成菜单
 * @param data
 */
function generateMenu(data){
	var menus = buildPermissionTree(data);
	flag = true;
	$.each(menus,function(i,e){
		$("#menu").accordion("add",{
			title:e.name,
			selected:flag,
			content:"<ul class='easyui-tree' id='tree"+e.id+"' ></ul>"
		});
		flag = false;
		//循环创建树的项
        $("#tree" + e.id).tree({
            data: e.children,
            lines: true,
            animate: true,
			loadFilter:changeName2Text,
            onClick: function (node) {
                if (node.url) {
                    var title = node.name;
                    var href = node.url;
                    var icon = node.icon|'default';
                    addTab(title,href,icon);
                } else {
                    if (node.state == "closed") {
                        $("#tree" + e.id).tree('expand', node.target);
                    } else if (node.state == 'open') {
                        $("#tree" + e.id).tree('collapse', node.target);
                    }
                }
            }
        });
	});
}

/**
 * 将数据中name属性赋值给text属性，满足tree的node节点数据
 * @param data
 * @returns {*}
 */
function changeName2Text(data) {
	if(data&&data.length>0){
		data.map(function(item,index){
			item.text = item.name;
			changeName2Text(item.children);
			return item;
		});
	}
	return data;
}

/**
 * 构建权限树菜单结构
 * @param data
 * @returns {*}
 */
function buildPermissionTree(data) {
    var maps = {},groups = {};
    if(!data)return [];
    data.map(function(item,index){
        maps[item.id] = item;
        var parentId = item.parentId;
        if(groups[parentId]){
            groups[parentId].push(item);
        }else{
            groups[parentId] = [item];
        }
    });
    var root = groups[""];
    changeProp(root,groups);
    return root;
}
function changeProp(data,groups){
    if(data){
        data.map(function(item,index){
            var children = groups[item.id];
            item.children = children;
            changeProp(item.children,groups);
            return item;
        });
    }
    return data;
}
function getRootMenu(){
    var ac = $("#menu").accordion("getSelected");
    if(!ac)return "系统首页";
    return ac.panel("options").title;
}
function getSecondMenu(){
    return $("#tabs").tabs("getSelected").panel("options").title;
}

$(function () {

	var currentMode = localStorage.getItem("workMode") || "month";  //从本地获取上次的工作模式，默认月报
	window.workMode = currentMode;
    $('#data-mode').combobox({value:currentMode});
    // $(".month-week").find(".mode-"+currentMode).addClass("active").siblings().removeClass("active");
    // $(".month-week>a").bind("click",function (e) {
		// if($(e.target).hasClass("active")){
		// 	return false;
		// }
		// var self  = this;
		// $(self).addClass("active").siblings().removeClass("active");
		// window.workMode = $(self).data("mode");
		// localStorage.setItem("workMode",window.workMode);   //将工作模式设置到本地内存
		// // 页面刷新
		// window.location.reload();
    // });

    $("#data-mode").combobox({
        onChange:function (e) {
            if(!e){
                window.location.reload();
               return
            }
            window.workMode = e;
            localStorage.setItem("workMode",window.workMode);   //将工作模式设置到本地内存
            // 页面刷新
            window.location.reload();
        }
    });
	//获取用户以及菜单权限
	$.ajax({
		url:config.url+"/user/user-info",
		type:'get',
		xhrFields:{withCredentials:true},
		success:function (data) {
			if(data.code==200){
			    // debugger;
                var user = data.data;
                if(user){
                    window.currentUser = user;
                    $("#username").html(user);
				}
				if(data.permissions){
                	generateMenu(data.permissions);
				}
				if(data.categories){
				    window.userCategoryManageList = data.categories;
                    //根据code排序
                    window.parent.userCategoryManageList.sort(function(a, b) {
                        return parseInt(a.code, 10) - parseInt(b.code, 10);
                    });
                }
                if(data.roles){
                    window.roles =data.roles;
                }
			}else if(data.code==401){
                window.location.href="/webapp";
            }
        },
		error:function (data) {
		    if("error"==data.statusText){
		        window.location.href="/webapp";
            }
        }
	});
	//获取年月周
	$.ajax({
		url:config.url+"/weekConfig/getCurrentPeriod",
		type:'get',
        data:{reportType:currentMode.toUpperCase()},
		xhrFields:{withCredentials:true},
		success:function (data) {
            if(data.code==401){
                window.location.href="/webapp";
            }
			window.timeData = data;
        },
		error:function (data) {
            if("error"==data.statusText){
                window.location.href="/webapp";
            }
        }
	});

	//获取年份
    $.ajax({
        url:config.url+"/weekConfig/getYears",
        type:'get',
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data.code==401){
                window.location.href="/webapp";
            }
            window.years = data;
        },
        error:function (data) {
            if("error"==data.statusText){
                window.location.href="/webapp";
            }
        }
    });
});